package com.ys.controller.api.account;

import com.ys.config.MenuId;
import com.ys.entity.account.TcwAdvanceAccountRecharge;
import com.ys.entity.account.TcwAdvanceAccountReimbursement;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsGridCol;
import com.ys.service.account.TcwAdvanceAccountReimbursementService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 预支账户报销单
 */
@Controller
@RequestMapping("/api/inter/tcwAdvanceAccountReimbursement")
public class ApiInterTcwAdvanceAccountReimbursementController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwAdvanceAccountReimbursementController.class);

    @Autowired
    private CommonApiService<TcwAdvanceAccountReimbursement> commonApiService;
    @Autowired
    private TcwAdvanceAccountReimbursementService tcwAdvanceAccountReimbursementService;
    @Autowired
    private YspTaskService yspTaskService;

    private final String PERMISSIONS_ADD = "tcwAdvanceAccountReimbursement:add";

    private final long GUID = 17L;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwAdvanceAccountReimbursement setSeachSql(TcwAdvanceAccountReimbursement cond){

        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
            .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime");//审核时间

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
            .addField("U.UserId + '/' + U.UserName AS createUserName");//制单人

        cond.addLeftJoin("TCW_AdvanceAccount AA ON AA.Id = A.AdvanceAccountId ")
                .addField("AA.Code AS code")//预支账户编码
                .addField("AA.Name AS name");//付款账户名称

        cond.addLeftJoin("TS_OrganizationInfo O ON AA.Orgid = O.Orgid ")
                .addField("O.OrgName AS orgName");//账户管理部门

        /*
        cond.addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id")
                .addLeftJoin("TS_UserInfo B on  B.UserId = UB.UserId")
                .addField("B.DeptName AS deptName");//账户管理部门

         */

        //列表
        cond.addLeftJoin("(SELECT I.Pbid,SUM ( D.TotalPrice ) AS totalPriceByThis FROM TCW_AdvanceAccountReimbursementItem I LEFT JOIN TCW_AdvanceAccountDetail D ON I.AdvanceAccountDetailId = D.Id GROUP BY I.Pbid) D1 on D1.Pbid = A.Bid")
                .addField("ISNULL(D1.totalPriceByThis, 0) AS totalPriceByThis");//本次报销金额

        //明细2
        cond.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByOther FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode NOT IN ('YZZHLX000','YZZHLX001') GROUP BY Pid) D2 on D2.Pid = A.AdvanceAccountId AND 1=1")
                .addField("ISNULL(D2.totalPriceByOther, 0) AS totalPriceByOther");//台账总金额
        //明细3
        cond.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceBySubmit FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX001' GROUP BY Pid) D3 on D3.Pid = A.AdvanceAccountId AND 1=1")
                .addField("ISNULL(D3.totalPriceBySubmit, 0) AS totalPriceBySubmit");//台账报销金额,字段“总额”之和（预支类型为报销）


        /*
        cond.addLeftJoin("TS_UserBankInfo UB2 ON A.UserBankInfoId = UB2.Id")
                .addField("UB2.Vyhzhmc AS vyhzhmc")//收款银行账户名称
                .addField("UB2.Vkhh AS vkhh")//收款开户行
                .addField("UB2.Vyhzh AS vyhzh");//收款银行账户编码
         */
        cond.addLeftJoin("TS_UserBankInfo UB ON A.UserBankInfoId = UB.Id AND A.AccountType=0")
                .addLeftJoin("TCW_PartnerBankInfo PB ON A.PartnerBankInfoId = PB.Id AND A.AccountType=1")
                .addField("CASE WHEN A.AccountType=0 THEN UB.Vyhzhmc ELSE PB.Vyhzhmc END _ys_vyhzhmc")//收款银行账户名称
                .addField("CASE WHEN A.AccountType=0 THEN UB.Vkhh ELSE PB.Vkhh END _ys_vkhh")//收款开户行
                .addField("CASE WHEN A.AccountType=0 THEN UB.Vyhzh ELSE PB.Vyhzh END _ys_vyhzh");//收款银行账户编码


        cond.addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyVid ")
                .addField("CI.Vname AS vname");//所属公司

        cond.addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm ")
                .addField("C.Vgsjc AS vgsjc");//运营公司简称

        cond.addLeftJoin("TB_CompanyBankInfo CB ON A.CompanyBankInfoId = CB.Id")
                .addField("CB.Vyhzhmc AS pvyhzhmc")//付款银行账户名称
                .addField("CB.Vkhh AS pvkhh")//付款开户行
                .addField("CB.Vyhzh AS pvyhzh")//付款银行账户编码
                .addLeftJoin("TS_UserChange QWE ON QWE.Id = A.CreateChangeId")
                .addField("(QWE.UserId + '/' + QWE.UserName) AS _ys_nameLinked")//制单人

                .addLeftJoin("TS_UserInfo CU ON CU.UserId = QWE.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId")//用户所属机构
                .addField("QWE.UserId AS userld")
                .addField("CU.OrgId AS orgId");

        //排序
        cond.setOrderby("A.Bid DESC");
        cond = commonApiService.dataAuth(MenuId.TCW_AdvanceAccountReimbursement, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwAdvanceAccountReimbursement:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwAdvanceAccountReimbursement cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwAdvanceAccountReimbursement cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_AdvanceAccountReimbursement)
                    .where("A.Code != 'ope'")
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcwAdvanceAccountReimbursement> util = new ExportExcelUtils<>(new TcwAdvanceAccountReimbursement());
            String toFilePath = util.exportExcel(listData, listField, "预支账户报销单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 导出 - 子列表
     */
    @RequestMapping("/exportByItem")
    @ResponseBody
    public R exportByItem(@RequestParam Map<String, Object> params){
        try {
            String bid = params.get("bid").toString();

            //获取菜单字段数据
            List<YsGridCol> listField = new YsGridCol()
                    .setGridId(GUID)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = tcwAdvanceAccountReimbursementService.getItemList(bid);
            //处理数据
            ExportExcelUtils<TcwAdvanceAccountReimbursement> util = new ExportExcelUtils<>(new TcwAdvanceAccountReimbursement());
            String toFilePath = util.exportExcelByGrid(listData, listField, "预支账户报销单列表【"+bid+"】");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountReimbursementService.add(params,MenuId.TCW_AdvanceAccountReimbursement);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 编辑
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountReimbursementService.update(params,MenuId.TCW_AdvanceAccountReimbursement);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwAdvanceAccountReimbursementService.flowPass(id, ShiroUtils.getUserId());
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("流转出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        TcwAdvanceAccountReimbursement entity = new TcwAdvanceAccountReimbursement().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        TcwAdvanceAccountReimbursement entity = new TcwAdvanceAccountReimbursement().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("驳回出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/delete")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return tcwAdvanceAccountReimbursementService.del(id);
        } catch (Exception e) {
            logger.error("删除表出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


}